class WxRequest {
  defaults = {
    baseURL: '',
    url: '',
    data: null,
    method: 'Get',
    header: {
      'content-type': 'application/json'
    },
    timeout: 6000,
    isLoading: true
  }
  // 拦截器
  interceptors = {
    request: (config) => config,
    response: (response) => response
  }

  // 定义请求队列
  queue = []

  // constructor的params是实例传过来的参数
  constructor(params = {}) {
    // console.log(params)
    this.defaults = Object.assign({}, this.defaults, params)
  }
  // options是请求页面传过来的参数
  request(options) {
    this.timerId && clearTimeout(this.timerId)
    // console.log(options)
    options.url = this.defaults.baseURL + options.url
    options = { ...this.defaults, ...options }
    if (options.isLoading && options.method === 'UPLOAD') {
      // 添加loading效果
      // wx.showLoading()
      this.queue.length === 0 && wx.showLoading()
      this.queue.push('request')
    }

    options = this.interceptors.request(options)

    return new Promise((resolve, reject) => {
      if (options.method === 'UPLOAD') {
        wx.uploadFile({
          ...options,
          success: (res) => {
            res.data = JSON.parse(res.data)
            const mergeRes = Object.assign({}, res, { config: options, isSuccess: true })
            resolve(this.interceptors.response(mergeRes))
          },

          fail: (err) => {
            res.data = JSON.parse(res.data)
            const mergeErr = Object.assign({}, err, { config: options, isSuccess: true })
            reject(this.interceptors.response(mergeErr))
          },
          complete: () => {
            this.queue.pop()
            this.queue.length === 0 && wx.hideLoading()
          }
        })
      } else {
        wx.request({
          ...options,
          success: (res) => {
            // console.log(res)
            const mergeRes = Object.assign({}, res, { config: options, isSuccess: true })
            resolve(this.interceptors.response(mergeRes))
            // console.log(res);
          },

          fail: (err) => {
            const mergeErr = Object.assign({}, err, { config: options, isSuccess: false })
            reject(this.interceptors.response(mergeErr))
          },

          // 接口调用结束的回调函数（调用成功、失败都会执行）
          complete: () => {
            // wx.hideLoading()
            if (options.isLoading) {
              this.queue.pop()
              this.queue.length === 0 && this.queue.push('request')
              this.timerId = setTimeout(() => {
                this.queue.pop()
                this.queue.length === 0 && wx.hideLoading()
                clearTimeout(this.timerId)
              }, 1)
            }
          }
        })
      }
    })
  }
  // 封装 GET 实例方法
  get(url, data = {}, config = {}) {
    return this.request(Object.assign({ url, data, method: 'GET' }, config))
  }
  // 封装 POST 实例方法
  post(url, data = {}, config = {}) {
    return this.request(Object.assign({ url, data, method: 'POST' }, config))
  }
  // 封装 Put 实例方法
  put(url, data = {}, config = {}) {
    return this.request(Object.assign({ url, data, method: 'PUT' }, config))
  }
  // 封装 DELETE 实例方法
  delete(url, data = {}, config = {}) {
    return this.request(Object.assign({ url, data, method: 'DELETE' }, config))
  }

  // 并发请求
  all(...promise) {
    // console.log(promise)
    return Promise.all(promise)
  }
  // 将头像放到服务器
  upload(url, filePath, name = 'file', config = {}) {
    return this.request(Object.assign({ url, filePath, name, method: 'UPLOAD' }, config))
  }
}

export default WxRequest
